//
//  WHMineController.m
//  SquirrelSeller
//
//  Created by 邓伟浩 on 2018/12/29.
//  Copyright © 2018 邓伟浩. All rights reserved.
//

#import "WHMineController.h"
#import "WHMenuTipsCell.h"
//#import "WHMineInfoCell.h"
#import "WHMineInfoView.h"

#import "WHFileManagerHelper.h"

#import "WHResetPasswordController.h" // 修改密码
#import "WHSettingController.h" // 设置
#import "WHAboutUsController.h" // 关于我们

@interface WHMineController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *dataTableView;

@property (nonatomic, strong) NSArray *tipsImageArray;
@property (nonatomic, strong) NSArray *tipsNameArray;

@end

@implementation WHMineController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.naviType = NaviTypeClear;
    
    self.navigationItem.title = @"个人中心";
    [self setUpNavigationItem];
    [self initParams];
    [self setUpTableView];
}

- (void)setUpNavigationItem {
    
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    rightButton.frame = CGRectMake(0, 0, 80, kNavBarHeight);
    NSAttributedString *attStr = [[NSAttributedString alloc] initWithString:@"退出登录" attributes:@{NSFontAttributeName:SYSTEMFONT(kRealwidth(15)), NSForegroundColorAttributeName:KWhiteColor}];
    [rightButton setAttributedTitle:attStr forState:UIControlStateNormal];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    [rightButton addTarget:self action:@selector(logoutClicked:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = rightItem;
}

- (void)initParams {
    _tipsImageArray = @[@"mine_resetPassword_icon", @"mine_setting_icon", @"mine_clearCache_icon", @"mine_aboutUs_icon"];
    _tipsNameArray = @[@"修改密码", @"设置中心", @"清除缓存", @"关于我们"];
}

- (void)setUpTableView {
    UITableView *dataTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    dataTableView.delegate = self;
    dataTableView.dataSource = self;
    [self.view addSubview:dataTableView];
    
    [dataTableView registerClass:[WHMenuTipsCell class] forCellReuseIdentifier:NSStringFromClass([WHMenuTipsCell class])];
//    [dataTableView registerClass:[WHMineInfoCell class] forCellReuseIdentifier:NSStringFromClass([WHMineInfoCell class])];
    
    dataTableView.bounces = NO;
    dataTableView.tableHeaderView = [self tableHeaderView];
    dataTableView.tableFooterView = [UIView new];
    dataTableView.backgroundColor = KWhiteColor;
    dataTableView.separatorColor = CLineColor;
    dataTableView.separatorInset = UIEdgeInsetsMake(0, KNormalSpace, 0, -KNormalSpace);
    
    [dataTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.mas_equalTo(self.view);
    }];
    _dataTableView = dataTableView;
}

- (UIView *)tableHeaderView {
    WHMineInfoView *infoView = [[WHMineInfoView alloc] init];
    infoView.frame = CGRectMake(0, 0, KScreenWidth, kRealwidth(320));
    
    infoView.phoneNumberLabel.text = NSStringFormat(@"%@ %@", userManager.detailUserInfo.cardName?:@"数据异常", userManager.detailUserInfo.mobile?:@"数据异常");
    infoView.nameLabel.text = userManager.detailUserInfo.nickName;
    [infoView.headImageView setImageWithURL:[NSURL URLWithString:userManager.detailUserInfo.avatar] placeholder:IMAGE_NAMED(@"mine_defaultHeader")];
    
    return infoView;
}

//- (UIView *)tableFootView {
//    UIView *tableFootView = [[UIView alloc] init];
//    tableFootView.frame = CGRectMake(0, 0, KScreenWidth, kRealwidth(75));
//
//    UIButton *logoutButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    logoutButton.frame = CGRectMake(kRealwidth(32), kRealwidth(10), KScreenWidth-2*kRealwidth(32), kRealwidth(45));
//    ViewRadius(logoutButton, kRealwidth(45)/2);
//    [tableFootView addSubview:logoutButton];
//    [logoutButton addTarget:self action:@selector(logoutClicked:) forControlEvents:UIControlEventTouchUpInside];
//    NSString *logoutTitle = @"退出登录";
//    NSAttributedString *attributeStr = [[NSAttributedString alloc] initWithString:logoutTitle attributes:@{NSFontAttributeName:SYSTEMFONT(kRealwidth(17)), NSForegroundColorAttributeName:KWhiteColor}];
//    [logoutButton setAttributedTitle:attributeStr forState:UIControlStateNormal];
//    logoutButton.backgroundColor = CMDarkOrangeColor;
//
//    return tableFootView;
//}

#pragma mark - —————— UITableViewDelegate & UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _tipsNameArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//        WHMineInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([WHMineInfoCell class]) forIndexPath:indexPath];
//        cell.phoneNumberLabel.text = NSStringFormat(@"%@ %@", userManager.detailUserInfo.cardName?:@"数据异常", userManager.detailUserInfo.mobile?:@"数据异常");
//        cell.nameLabel.text = userManager.detailUserInfo.nickName;
//        [cell.headImageView setImageWithURL:[NSURL URLWithString:userManager.detailUserInfo.avatar] placeholder:IMAGE_NAMED(@"mine_defaultHeader")];
//
//        return cell;
    
    WHMenuTipsCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([WHMenuTipsCell class]) forIndexPath:indexPath];
    
    NSString *tipName = _tipsNameArray[indexPath.row];
    cell.tipsImageView.image = IMAGE_NAMED(_tipsImageArray[indexPath.row]);
    cell.tipsLabel.text = tipName;
    
    if ([tipName isEqualToString:@"清除缓存"]) {
        cell.descriptionLabel.text = @"正在计算...";
        UIActivityIndicatorView *loadingView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        [loadingView startAnimating];
        cell.accessoryView = loadingView;
        cell.userInteractionEnabled = NO;
        cell.rightImageView.hidden = YES;
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            float size = [WHFileManagerHelper readCacheSize];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                dispatch_async(dispatch_get_main_queue(), ^{
                    cell.accessoryView = nil;
                    cell.descriptionLabel.text = NSStringFormat(@"%.2f MB", size);
                    cell.userInteractionEnabled = YES;
                    cell.rightImageView.hidden = NO;
                });
            });
        });
    } else {
        cell.descriptionLabel.text = @"";
        cell.userInteractionEnabled = YES;
        cell.rightImageView.hidden = NO;
    }
    
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [UIView new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return kRealwidth(10);
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *tipName = _tipsNameArray[indexPath.row];
    if ([tipName isEqualToString:@"修改密码"]) {
        WHResetPasswordController *resetPassword = [[WHResetPasswordController alloc] init];
        [self.navigationController pushViewController:resetPassword animated:YES];
    }
    if ([tipName isEqualToString:@"设置"]) {
        WHSettingController *setting = [[WHSettingController alloc] init];
        [self.navigationController pushViewController:setting animated:YES];
    }
    if ([tipName isEqualToString:@"清除缓存"]) {
        WHMenuTipsCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        
        [self clearCacheClick:cell];
    }
    if ([tipName isEqualToString:@"关于我们"]) {
        WHAboutUsController *aboutUs = [[WHAboutUsController alloc] init];
        [self.navigationController pushViewController:aboutUs animated:YES];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kRealwidth(70);
}

#pragma mark - —————— 事件 ——————
- (void)logoutClicked:(UIButton *)button {
    [WHView showAlertwithTitle:nil message:@"确定退出账号吗?" okAction:^(UIAlertAction *action) {
        [userManager logout:nil];
    } cancelAction:nil];
}

- (void)clearCacheClick:(WHMenuTipsCell *)cell {
    if ([cell.descriptionLabel.text isEqualToString:@"0.00 MB"]) {
        [WHView showMessage:@"没有缓存" inView:nil];
        return;
    }
    
    [WHView showAlertwithTitle:nil message:@"确定清除缓存吗?" okAction:^(UIAlertAction *action) {
        [self clearCache:cell];
    } cancelAction:nil];
}

- (void)clearCache:(WHMenuTipsCell *)cell {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [WHFileManagerHelper clearFile];
        float size = [WHFileManagerHelper readCacheSize];
        dispatch_async(dispatch_get_main_queue(), ^{
            cell.descriptionLabel.text = NSStringFormat(@"%.2f MB", size);
        });
    });
}

@end
